package com.antoco.controlcenter.model.video.activity;

import android.Manifest;

import android.content.Intent;
import android.content.IntentFilter;

import android.media.Image;
import android.media.MediaScannerConnection;

import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.antoco.controlcenter.adapter.ShowListRecyclerViewAdapter;
import com.antoco.controlcenter.base.BaseFragmentActivity;
import com.antoco.controlcenter.base.Constants;
import com.antoco.controlcenter.base.PowerReceiver;
import com.antoco.controlcenter.comm.PropertyBase;
import com.antoco.controlcenter.R;
import com.antoco.controlcenter.comm.RobotMoveState;
import com.antoco.controlcenter.entity.ConfigEntity;
import com.antoco.controlcenter.entity.ConnectEntity;
import com.antoco.controlcenter.entity.DisplayEntity;
import com.antoco.controlcenter.entity.InstructEntity;
import com.antoco.controlcenter.entity.OperatorsEntity;
import com.antoco.controlcenter.entity.ParserEntity;
import com.antoco.controlcenter.entity.PropertyEntity;
import com.antoco.controlcenter.entity.RebotEntity;
import com.antoco.controlcenter.entity.VideoEntity;
import com.antoco.controlcenter.event.DataRefreshEventEntity;
import com.antoco.controlcenter.iface.IBatteryListener;
import com.antoco.controlcenter.iface.IPictListener;
import com.antoco.controlcenter.model.video.entity.OsdEntity;
import com.antoco.controlcenter.model.video.fragment.ContorFragmet;
import com.antoco.controlcenter.model.video.iface.IMoveSpeedListener;
import com.antoco.controlcenter.model.video.iface.IOsdView;
import com.antoco.controlcenter.model.video.presenter.OsdPresenter;
import com.antoco.controlcenter.model.video.rxjava.MoveRobotEventing;
import com.antoco.controlcenter.utils.NetworkUtils;
import com.antoco.controlcenter.utils.XmlPullParserUtil;
import com.antoco.controlcenter.view.BatteryView;
import com.antoco.controlcenter.view.FloatView;
import com.antoco.controlcenter.view.GameRotateView;
import com.antoco.controlcenter.view.VlcManager;
import com.antoco.controlcenter.comm.RobotHandler;
import com.antoco.controlcenter.iface.IRecodeEventListener;
import com.antoco.controlcenter.utils.BitmapUtil;

import com.antoco.controlcenter.utils.TimeUtil;
import com.antoco.controlcenter.utils.ToastUtils;

import org.angmarch.views.NiceSpinner;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.videolan.libvlc.util.VLCVideoLayout;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.github.controlwear.virtual.joystick.android.JoystickView;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static com.antoco.controlcenter.base.Constants.CONFIG_MAP;
import static com.antoco.controlcenter.base.Constants.VIEW_MAP;

public class ControlActivity extends BaseFragmentActivity implements IRecodeEventListener, ShowListRecyclerViewAdapter.OnItemClickListener, IBatteryListener, IOsdView , IMoveSpeedListener {
    @BindView(R.id.my_recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.btn_record)
    ImageButton btnRecord;
    @BindView(R.id.btn_switch)
    ImageButton btnSwitch;
    @BindView(R.id.btn_snapshort)
    ImageButton btnSnapshort;
    @BindView(R.id.btn_setting)
    ImageButton btnSetting;
    @BindView(R.id.btn_float)
    ImageButton btnFloat;

    @BindView(R.id.layout_player)
    VLCVideoLayout playerView;


    @BindView(R.id.recode_time)
    TextView recodeTimeTv;
    String time;
    FloatView floatView;
    @BindView(R.id.batter_view)
    BatteryView batteryView;
    @BindView(R.id.batter_device)
    BatteryView batterDevice;

    @BindView(R.id.joystick)
    JoystickView joystick;
    @BindView(R.id.nice_spinner)
    NiceSpinner niceSpinner;
    @BindView(R.id.control_view_ll)
    LinearLayout controlViewll;
    @BindView(R.id.image_roll)
    ImageView imageRollView;
    @BindView(R.id.image_paith)
    ImageView imagePaView;

    private String[] configList; //机器人配置列表
    private RobotHandler robothandler; //机器人控制器
    private VlcManager vlcManager; //视频控制器
    private Runnable vlcRunnable;
    private ShowListRecyclerViewAdapter adapter;
    private List<RebotEntity> mlist = new ArrayList<>();
    private LinearLayoutManager mLayoutManager;
    private String frontUrl;
    private String postUrl;
    private String imagePath = null;
    private MediaScannerConnection mMediaScannerConnection;  //截图事件
    private Image image;
    private OsdPresenter mOsdPresenter = new OsdPresenter(this, this);
    private float toDegrees = 0;
    private IPictListener iPictListener;
    //悬浮窗
    private static int GET_DIALOG_PERMISSION = 6;
    private PowerReceiver mBatInfoReceiver;

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            Message msg = uiHandler.obtainMessage(20);
            uiHandler.sendMessage(msg);
        }

    };

    Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 20:
                    disRecord();
                    time = TimeUtil.startTime(time, 1);
                    recodeTimeTv.setText(time);
                    uiHandler.postDelayed(mRunnable, 1000);
                    break;
            }
        }
    };

    @Override
    protected int getContentViewId() {
        return R.layout.activity_control;
    }

    @Override
    protected void initBundleData() {
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }

    }

    @Override
    protected void initView() {
        registeredEventBus();
        initAdapter();
        robothandler = new RobotHandler();
        initGroundView();
        initFloat();
        initLayout();

        switchConfig(0);
        initMedia();
    }

    @Override
    protected void initData() {
        mBatInfoReceiver = new PowerReceiver(this);
        presentersList.add(mOsdPresenter);
    }

    //预加载 控制视图
    private void initGroundView() {
        try {
            configList = this.getAssets().list("config");
            for (String xml : configList) {
                ConfigEntity configEntity = XmlPullParserUtil.xmlPullParser(this, xml);
                OperatorsEntity operatorsEntity = configEntity.getOperatorsEntity();
                SoftReference softReference = new SoftReference(new ContorFragmet(robothandler, operatorsEntity.getGroupList(), operatorsEntity.getSliderList()));
                VIEW_MAP.put(xml, softReference);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void initFloat() {
        if (Build.VERSION.SDK_INT >= 23) { // Android6.0及以后需要动态申请权限
            if (!Settings.canDrawOverlays(this)) {
                //启动Activity让用户授权
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, GET_DIALOG_PERMISSION);
            } else {
                createFloatView();
            }
        } else {
            // 弹出悬浮窗
            createFloatView();
        }

    }

    private void createFloatView() {
        floatView = new FloatView();
//        floatView.play(url);
    }


    public void iniyPayer() {
        // 视频播放
        if (vlcManager == null) {
            vlcManager = new VlcManager(this, playerView);
           // vlcManager.setFullSrcee();
        }
        vlcManager.setiRecodeEventListener(this);
    }

    public void takeScreenShot() {
        if (!TextUtils.isEmpty(vlcManager.takeScreenShot())) {
            scanFile(vlcManager.takeScreenShot(), false);
        }
    }

    private void initMedia() {
        //1.创建MediaScannerConnection
        mMediaScannerConnection = new MediaScannerConnection(this, null);
        //调用connect
        mMediaScannerConnection.connect();
        mapRequestPermissions();

    }


    private void initAdapter() {
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        adapter = new ShowListRecyclerViewAdapter(this, mlist, this);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        adapter.setIBatteryListener(this);
        mRecyclerView.setAdapter(adapter);
    }

    private void degressTo() {
        for (RebotEntity entity : mlist) {
            String[] pas = entity.getValue().split("：");
            if (entity.getValue().contains("横滚角")) {
                imageRollView.setImageResource(R.mipmap.zcj_roll);
                if (pas.length >= 2) {
                    String rollstr = pas[1].replace("°", "");
                    float roll = Float.parseFloat(rollstr);
                    float degree = Math.abs(Math.abs(roll) - Math.abs(toDegrees));
                    if (degree >= 5) {
                        startRotateView(R.mipmap.zcj_roll, roll);
                    }

                }

            }
            if (entity.getValue().contains("俯仰角")) {
                imagePaView.setImageResource(R.mipmap.zcj_pitch);
                if (pas.length >= 2) {
                    String pitchstr = pas[1].replace("°", "");
                    float pitch = Float.parseFloat(pitchstr);
                    float degree = Math.abs(Math.abs(pitch) - toDegrees);
                    if (degree >= 5) {
                        startRotateView(R.mipmap.zcj_pitch, pitch);
                    }
                }
            }
        }
    }

    private void startRotateView(int pic, float degrees) {
        GameRotateView pitchView = new GameRotateView(this, pic);
        iPictListener = pitchView.getIPictListener();
        //imageRoll.addView(pitchView);
        iPictListener.onChangeAngle(degrees);
    }


    private void initLayout() {

        // 虚拟摇杆
        joystick.setOnMoveListener((angle, strength) -> {
            if (strength > 10) {
                if (45 < angle && angle < 135) {
                    Constants.MOVESTATE = RobotMoveState.FORWARD;
                }
                if (135 < angle && angle < 225) {
                    Constants.MOVESTATE = RobotMoveState.LEFT;
                }
                if (225 < angle && angle < 315) {
                    Constants.MOVESTATE = RobotMoveState.BACKWARD;
                }
                if (315 < angle || angle < 45) {
                    Constants.MOVESTATE = RobotMoveState.RIGHT;
                }
            } else {
                Constants.MOVESTATE = RobotMoveState.STOP;
            }
        });

        btnSetting.setImageDrawable(BitmapUtil.wrappedDrawable(this, getDrawable(R.mipmap.outline_settings_black), R.color.viewfinder_laser));
        btnRecord.setImageDrawable(BitmapUtil.wrappedDrawable(this, getDrawable(R.mipmap.round_video_call_black), R.color.white));
        btnSnapshort.setImageDrawable(BitmapUtil.wrappedDrawable(this, getDrawable(R.mipmap.round_camera_alt_black), R.color.white));
        btnSwitch.setImageDrawable(BitmapUtil.wrappedDrawable(this, getDrawable(R.mipmap.round_missed_video_call_black), R.color.white));
        btnFloat.setImageDrawable(BitmapUtil.wrappedDrawable(this, getDrawable(R.mipmap.round_desktop_windows_black), R.color.white));


        List<String> dataset = new LinkedList<>(Arrays.asList(configList));
        niceSpinner.setBackgroundResource(R.drawable.shape_nicespinner);
        niceSpinner.attachDataSource(dataset);
        niceSpinner.setOnSpinnerItemSelectedListener((parent, view, position, id) -> {
            Log.d("===========>", String.valueOf(position));
            switchConfig(position);
        });


    }

    @OnClick({R.id.btn_record, R.id.btn_switch, R.id.btn_snapshort, R.id.btn_setting, R.id.btn_float,})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_record:

                if (null == vlcManager || !vlcManager.isPlaying()) {
                    ToastUtils.showToast(ControlActivity.this, "当前不存在正在播放的视频，无法开启录像");
                    return;
                }
                if (vlcManager.isRecording()) {
                    vlcManager.recordStop();
                } else {
                    if (!NetworkUtils.isNetworkConnected()) {
                        ToastUtils.showToast(ControlActivity.this, "当前无网络，无法开启录像");
                        return;
                    }
                    onStartRecode();
                    imagePath = vlcManager.recordStart(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath());
                }
                break;
            case R.id.btn_switch:
                switchVideoUrl();
                break;
            case R.id.btn_snapshort:
                if (!vlcManager.isPlaying()) {
                    ToastUtils.showToast(this, "视频未播放，无法截屏");
                    return;
                }
                btnFloat.setImageDrawable(BitmapUtil.wrappedDrawable(ControlActivity.this, getDrawable(R.mipmap.round_desktop_windows_black), R.color.white));
                takeScreenShot();
                break;
            case R.id.btn_setting: //打开侧滑菜单
                if (controlViewll.getVisibility() == View.GONE) {
                    controlViewll.setVisibility(View.VISIBLE);
                    btnSetting.setImageDrawable(BitmapUtil.wrappedDrawable(ControlActivity.this, getDrawable(R.mipmap.outline_settings_black), R.color.viewfinder_laser));
                } else {
                    controlViewll.setVisibility(View.GONE);
                    btnSetting.setImageDrawable(BitmapUtil.wrappedDrawable(ControlActivity.this, getDrawable(R.mipmap.outline_settings_black), R.color.white));

                }

                break;

            case R.id.btn_float:
                if (floatView.isWindowShowing()) {
                    btnFloat.setImageDrawable(BitmapUtil.wrappedDrawable(ControlActivity.this, getDrawable(R.mipmap.round_desktop_windows_black), R.color.white));
                    floatView.removeWindow();
                } else {
                    btnFloat.setImageDrawable(BitmapUtil.wrappedDrawable(ControlActivity.this, getDrawable(R.mipmap.round_desktop_windows_black), R.color.viewfinder_laser));
                    floatView.play(postUrl);
                }
                break;
        }
    }

    private void disRecord() {
        if (!NetworkUtils.isNetworkConnected() && null != vlcManager && vlcManager.isRecording()) {
            vlcManager.recordStop();
        }
    }


    private void clearConfig() {
        robothandler.clearConfig();
        MoveRobotEventing.getInstance().clear();
    }

    private void initConfig(int index) {
        String xml = configList[index];
        replaceView(VIEW_MAP.get(xml).get());
        ConfigEntity configEntity = CONFIG_MAP.get(xml);

        ConnectEntity connectEntity = configEntity.getConnectEntity();
        robothandler.setCommString(connectEntity.getIp() + ":" + connectEntity.getPort());
        // url
        List<VideoEntity> videoEntityList = configEntity.getVideoEntityList();
        if (null != videoEntityList && !videoEntityList.isEmpty()) {
            frontUrl = videoEntityList.get(0).getUrl();
            if (videoEntityList.size() >= 2) {
                postUrl = videoEntityList.get(1).getUrl();
            }
        }
        // 指令集
        List<InstructEntity> instructEntityList = configEntity.getInstructionsList();
        if (null != instructEntityList && !instructEntityList.isEmpty()) {
            instructEntityList.forEach(entity -> {
                robothandler.addInstruct(entity.getName(), entity.getValue());
            });
        }
        // 属性解析
        List<PropertyEntity> propertyList = configEntity.getPropertyList();
        List<PropertyBase> propertyBaseList = new ArrayList<>();
        if (null != propertyList && !propertyList.isEmpty()) {
            propertyList.forEach(propertyEntity -> {
                String type = TextUtils.isEmpty(propertyEntity.getType()) ? "Integer" : propertyEntity.getType();
                PropertyBase property = new PropertyBase(propertyEntity.getName(), type);
                if (!TextUtils.isEmpty(propertyEntity.getValue())) {
                    property.setNumberValue(propertyEntity.getValue());
                }
                //display解析
                DisplayEntity displayEntity = propertyEntity.getDisplayEntity();
                if (null != displayEntity) {
                    property.initDisplay(displayEntity.getTemplate());
                }

                //parser解析
                ParserEntity parserEntity = propertyEntity.getParserEntity();
                if (null != parserEntity) {
                    String parserType = TextUtils.isEmpty(parserEntity.getType()) ? "u32" : parserEntity.getType();
                    long mask = TextUtils.isEmpty(parserEntity.getMask()) ? 0xFFFFFFFF : Long.parseLong(parserEntity.getMask().replaceAll("^0[x|X]", ""), 16);
                    double accuracy = TextUtils.isEmpty(parserEntity.getAccuracy()) ? 1 : Double.parseDouble(parserEntity.getAccuracy());
                    double correct = TextUtils.isEmpty(parserEntity.getCorrect()) ? 0 : Double.parseDouble(parserEntity.getCorrect());
                    String meta = TextUtils.isEmpty(parserEntity.getMeta()) ? "" : parserEntity.getMeta();
                    int offset = TextUtils.isEmpty(parserEntity.getOffset()) ? 0 : Integer.parseInt(parserEntity.getOffset());
                    int length = TextUtils.isEmpty(parserEntity.getLength()) ? 0 : Integer.parseInt(parserEntity.getLength());
                    property.initParser(offset
                            , length
                            , parserType, mask, accuracy, correct, meta);
                }
                propertyBaseList.add(property);
            });
        }
        robothandler.propertyManager.setProperties(propertyBaseList);

    }


    private void switchVideoUrl() {
        String temp = frontUrl;
        frontUrl = postUrl;
        postUrl = temp;
        if (!TextUtils.isEmpty(frontUrl)) {
            vlcManager.play(frontUrl);
        }

        if (!TextUtils.isEmpty(postUrl) && floatView.isWindowShowing()) {
            floatView.play(postUrl);
        }
    }

    private void switchConfig(int index) {
        // 删除现有机器人
        if (robothandler != null) {
            robothandler.stopCommunication();
        }
        // 载入配置文件
        clearConfig();
        initConfig(index);
        iniyPayer();
        startPlayRunable();
        // 通信组件
        robothandler.startCommunication();
        initMove();
//            if (!TextUtils.isEmpty(postUrl)) {
//                floatView.play(postUrl);
//            }
        ToastUtils.showToast(this, frontUrl);
    }

    private void initMove() {
        MoveRobotEventing.getInstance().setInstructMap(robothandler.getInstructMap());
        MoveRobotEventing.getInstance().setNciQueue(robothandler.getNciQueue());
        MoveRobotEventing.getInstance().setMoveEventListener(robothandler.getMoveEventListener());
        MoveRobotEventing.getInstance().setiMoveSpeedListener(this);
        MoveRobotEventing.getInstance().setRobotGear(robothandler.getNumberValue());
        MoveRobotEventing.getInstance().startPatchObservable();
    }

    private void startPlayRunable() {
        if (null != vlcRunnable) {
            uiHandler.removeCallbacks(vlcRunnable);
            vlcRunnable = null;
        }

        vlcRunnable = () -> {
            if (!TextUtils.isEmpty(frontUrl)) {
                vlcManager.play(frontUrl);
            }
        };
        uiHandler.post(vlcRunnable);
    }


    /**
     * @param filePath 保存到本地的文件路径
     * @param isVideo  是否是视频
     */
    private void scanFile(String filePath, boolean isVideo) {
        if (mMediaScannerConnection != null) {
            if (isVideo) {
                //主动扫描视频
                mMediaScannerConnection.scanFile(filePath, "video/mp4");
            } else {
                //主动扫描图片
                mMediaScannerConnection.scanFile(filePath, "image/jpeg");
            }
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mBatInfoReceiver);
        if (null != floatView) {
            floatView.removeWindow();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (null == vlcManager) {
            return;
        }
        vlcManager.stop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null == vlcManager) {
            return;
        }
        MoveRobotEventing.getInstance().clear();
        VIEW_MAP.clear();
        floatView.removeWindow();
        uiHandler.removeCallbacksAndMessages(null);
        vlcManager.destroy();
        robothandler.destory();
        if (mMediaScannerConnection != null) {
            //释放连接
            mMediaScannerConnection.disconnect();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // 将结果转发给 EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        ToastUtils.showToast(this, "用户授权成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ToastUtils.showToast(this, "用户授权失败");
        //这时候，需要跳转到设置界面去，让用户手动开启。
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    private void mapRequestPermissions() {
        // SDK 小于23默认已经授权
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }
        String[] perms = {
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
        };
        String[] permsStr = {"允许读写存储卡",};

        int length = perms.length;
        for (int i = 0; i < length; i++) {
            if (!EasyPermissions.hasPermissions(this, perms)) {
                EasyPermissions.requestPermissions(this, permsStr[i],
                        i, perms);
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e("whh0914", "onActivityResult...requestCode=" + requestCode + ",resultCode=" + resultCode);
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GET_DIALOG_PERMISSION) {
            if (Build.VERSION.SDK_INT >= 23) { // Android6.0及以后需要动态申请权限
                if (Settings.canDrawOverlays(this)) {
                    // 弹出悬浮窗
                    createFloatView();
                } else {
                    ToastUtils.showToast(this, "not granted permission!");
                }
            }
        }
    }


    @Override
    public void onItemClick(int position) {

    }

    @Override
    public void onItemDelete(int position) {

    }

    @Override
    public void onItemLongClick(int position) {

    }

    @Override
    public void onStartRecode() {
        btnRecord.setEnabled(false);
        btnRecord.setImageDrawable(BitmapUtil.wrappedDrawable(ControlActivity.this, getDrawable(R.mipmap.round_video_call_black), R.color.viewfinder_laser));
    }

    @Override
    public void onStopRecode() {
        btnRecord.setEnabled(true);
        btnRecord.setImageDrawable(BitmapUtil.wrappedDrawable(ControlActivity.this, getDrawable(R.mipmap.round_video_call_black), R.color.white));

        if (!TextUtils.isEmpty(imagePath)) {
            ToastUtils.showToast(ControlActivity.this, imagePath);
            scanFile(imagePath, true);
            time = null;
            recodeTimeTv.setVisibility(View.GONE);
            uiHandler.removeCallbacks(mRunnable);
        }
    }

    @Override
    public void onChangeRecode(boolean isSuccess) {
        if (isSuccess) {
            btnRecord.setEnabled(true);
            btnRecord.setImageDrawable(BitmapUtil.wrappedDrawable(ControlActivity.this, getDrawable(R.mipmap.round_video_call_black), R.color.viewfinder_laser));
            ToastUtils.showToast(ControlActivity.this, "开启录像成功");
            recodeTimeTv.setVisibility(View.VISIBLE);
            time = TimeUtil.startTime(time, 0);
            recodeTimeTv.setText(time);
            uiHandler.postDelayed(mRunnable, 1000);
        } else {
            btnRecord.setEnabled(true);
            btnRecord.setImageDrawable(BitmapUtil.wrappedDrawable(ControlActivity.this, getDrawable(R.mipmap.round_video_call_black), R.color.white));
            ToastUtils.showToast(ControlActivity.this, "当前不存在正在播放的视频，无法开启录像");
            time = null;
            recodeTimeTv.setVisibility(View.GONE);
            uiHandler.removeCallbacks(mRunnable);
        }
    }

    private void replaceView(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.dock_operator, fragment);
        fragmentTransaction.commit();
    }

    @Override
    public void onChangeBattery(int level) {
        if (null != batteryView) {
            batteryView.setPower(level);
        }
    }

    @Override
    public void onDeviceBattery(int level) {
        if (null != batterDevice) {
            batterDevice.setPower(level);
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void closeLoading() {

    }

    @Override
    public void showToast(String msg) {

    }

    @Override
    public void showResult(OsdEntity entity) {
        if (null == entity) {
            return;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void DataRefreshEvent(DataRefreshEventEntity eventEntity) {
        List<String> stringList = robothandler.propertyManager.getAllDisplay();
        mlist.clear();
        List<RebotEntity> rebotEntityList = new ArrayList<>();
        stringList.forEach(entity -> {
            RebotEntity rebotEntity = new RebotEntity();
            rebotEntity.setValue(entity);
            rebotEntityList.add(rebotEntity);
        });
        adapter.refreshData(rebotEntityList);
        degressTo();
        // 移除粘性事件
        EventBus.getDefault().removeStickyEvent(eventEntity);
    }

    @Override
    public void moveSpeed() {
        MoveRobotEventing.getInstance().setRobotGear(robothandler.getNumberValue());
    }
}

